// Copyright 2017 Baidu Inc. All Rights Reserved.
// Author: Chen Xihao (chenxihao@baidu.com)
//
// Description: Adapter for hls

#ifndef BAIDU_IOT_TINYDU_IOT_OS_SRC_MEDIA_DATA_MANAGER_HLS_BAIDU_HLS_ADAPTER_H
#define BAIDU_IOT_TINYDU_IOT_OS_SRC_MEDIA_DATA_MANAGER_HLS_BAIDU_HLS_ADAPTER_H

#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>

#ifdef __cplusplus
extern "C" {
#endif

#define AES_BLOCK_SIZE      16 // Only support AES-128 */

typedef void* (*thread_entry)(void* p_this);
typedef int (*check_need_to_stop_hls)(void);

typedef struct hls_download_context {
    bool b_first_segment;
    void* stream;
    void* segment;
    int (*handle_segment_data)(
            void* stream,
            void* segment,
            const uint8_t* data,
            size_t len,
            int pos);
} hls_download_context;

typedef struct hls_adapter {
    // if size of download data bigger than limit, stop download
    int (*get_short_data_from_url)(
            const char* url,
            check_need_to_stop_hls need_stop,
            size_t limit,
            size_t position,
            uint8_t** data,
            size_t* len);

    uint32_t (*current_time)(void); // return microseconds
    int (*wait)(uint32_t millisec);

    void* (*thread_create)(void);
    void (*thread_destroy)(void* thread);
    int (*thread_start)(void* thread, thread_entry method, void* p_this);

    void* (*mutex_create)(void);
    int (*mutex_lock)(void* mutex);
    int (*mutex_unlock)(void* mutex);
    void (*mutex_destroy)(void* mutex);

    void* (*aes_context_create)();
    int (*aes_setkey_dec)(void* ctx, const uint8_t* key);
    int (*aes_decrypt_cbc)(void* ctx, size_t length, uint8_t iv[AES_BLOCK_SIZE],
            const uint8_t* input, uint8_t* output);
    void (*aes_context_destroy)(void* ctx);

    int (*download_segment)(
            const char* url,
            check_need_to_stop_hls need_stop,
            hls_download_context* context);

    int (*output_ts_data)(const uint8_t* data, size_t len, int pos);
} hls_adapter;

hls_adapter* create_hls_adapter(void);

#ifdef __cplusplus
}
#endif

#endif // BAIDU_IOT_TINYDU_IOT_OS_SRC_MEDIA_DATA_MANAGER_HLS_BAIDU_HLS_ADAPTER_H
